package com.sczmgk.hotline;

import android.app.ActivityManager;
import android.app.Application;
import android.content.pm.PackageManager;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.callback.MyMessageListener;
import com.hyphenate.easeui.controller.EaseUI;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.sczmgk.hotline.db.impl.UserDaoImpl;
import com.sczmgk.hotline.entity.ChatMsgBean;
import com.sczmgk.hotline.entity.User;
import com.sczmgk.hotline.utils.CacheUtils;
import com.sczmgk.hotline.utils.HxUtils;
import com.sczmgk.hotline.utils.MyLog;
import com.sczmgk.hotline.utils.PictureUtil;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import cn.jiguang.share.android.api.JShareInterface;

/**
 * Created by Administrator on 2017/4/12.
 */

public class MyApp extends Application {

    public static String loginUserName = "temp";
    public static final String HX_SERVICE = "kefu_01";
    public static String sessionKey;
    public static String randomCode;
    public static int type;
    public static String token;
    public static String imei = "imei-0000";
    public static String imsi = "0000";
    public static String areaCode;
    private static String TAG = MyApp.class.getSimpleName();
    public static int loginUserUid = -1;
    public static HttpUtils httpUtils;
    public static BitmapUtils bitmapUtils;
    public static BitmapUtils bitmapUtils_200;
    public static BitmapUtils bitmapUtils_400;
    public static boolean IS_CHAT_PROGUND = false;

    @Override
    public void onCreate() {
        super.onCreate();

        //友盟Debug
        MobclickAgent.setDebugMode(false);

        //上传异常日志到服务器
//        MyCrashHandler crashHandler = MyCrashHandler.getInstance();
//        crashHandler.setContext(getApplicationContext());
//        Thread.currentThread().setUncaughtExceptionHandler(crashHandler);

        initBitmapUtils();

        MyLog.d(TAG, "MyApp   --->  onCreate");

        PictureUtil.initImageMeasureSize(getApplicationContext());
        MyLog.d(TAG, "MyApp   --->  initImageFeather");

//        initImageLoader();//初始化imageLoader
        MyLog.d(TAG, "MyApp   --->  initImageLoader");

        //初始化极光分享
        JShareInterface.init(getApplicationContext());
        JShareInterface.setDebugMode(false);

        //社会化分享
//        PlatformConfig.setWeixin("wx8778351288963703", "51c56b886b5be869567dd389b3e5d1d6");
//
//        PlatformConfig.setQQZone("1105918930", "BwyBBwIvxm9HlGDm");
//        PlatformConfig.setSinaWeibo("2823425374", "d7aad2871f33894b7023eb77e7a804af");
//
//        try {
//            UMShareAPI.get(this);
//        } catch (Exception e) {
//            e.printStackTrace();
//            MyLog.d(TAG, "友盟不支持模拟器");
//        }

        initIM();

        initUserInfo();
    }

    private void initHttp() {
        httpUtils = new HttpUtils(15000);
        httpUtils.configDefaultHttpCacheExpiry(0);
    }

    /**
     * 取得app名
     *
     * @param pID
     * @return
     */
    private String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = this.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
                    // Log.d("Process", "Id: "+ info.pid +" ProcessName: "+
                    // info.processName +"  Label: "+c.toString());
                    // processName = c.toString();
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }

    public void initBitmapUtils() {
        bitmapUtils_200 = new BitmapUtils(getApplicationContext());
        bitmapUtils_200.configDefaultLoadFailedImage(R.drawable.load_default_center);
        bitmapUtils_200.configDefaultBitmapMaxSize(200, 200);
        bitmapUtils_200.configThreadPoolSize(1);
        bitmapUtils_200.configDefaultReadTimeout(2000);

        bitmapUtils_400 = new BitmapUtils(getApplicationContext());
        bitmapUtils_400.configDefaultLoadFailedImage(R.drawable.load_default_center);
        bitmapUtils_400.configDefaultBitmapMaxSize(400, 400);
        bitmapUtils_400.configThreadPoolSize(1);
        bitmapUtils_400.configDefaultReadTimeout(2000);

        bitmapUtils = new BitmapUtils(getApplicationContext());
        bitmapUtils.configDefaultBitmapMaxSize(100, 100);
        bitmapUtils.configThreadPoolSize(1);
        bitmapUtils.configDefaultReadTimeout(2000);
    }

    /**
     * 初始化环信
     */
    private void initIM() {
        int pid = android.os.Process.myPid();
        String processAppName = getAppName(pid);
        // 如果app启用了远程的service，此application:onCreate会被调用2次
        // 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
        // 默认的app会在以包名为默认的process name下运行，如果查到的process name不是app的process name就立即返回

        if (processAppName == null || !processAppName.equalsIgnoreCase("com.sczmgk.hotline")) {
            MyLog.e(TAG, "启用远程的service: " + processAppName);
            //"com.easemob.chatuidemo"为demo的包名，换到自己项目中要改成自己包名

            // 则此application::onCreate 是被service 调用的，直接返回
            return;
        }
//        FileUtil.initAppStoragePath(this);
        boolean init = EaseUI.getInstance().init(this, null);
        MyLog.d(TAG,"初始化环信  --->>> 状态: "+init);
        EaseUI.getInstance().setMyMessageListener(new MyMessageListener() {
            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                //注:未读的消息包含发送的消息
                //收到消息
                EMConversation conversation = EMClient.getInstance().chatManager().getConversation(HX_SERVICE);
                EMMessage lastMsg = conversation.getLastMessage();
                int pagesize = conversation.getUnreadMsgCount();
                MyLog.i(TAG, "未读消息的条数: " + pagesize);
                //SDK初始化加载的聊天记录为20条，到顶时需要去DB里获取更多
                //获取startMsgId之前的pagesize条消息，此方法获取的messages SDK会自动存入到此会话中，APP中无需再次把获取到的messages添加到会话中
                MyLog.d(TAG, "最后一条消息     msgid: " + lastMsg.getMsgId() + "    消息内容: " + lastMsg.getBody() + "----此消息为接收,将消息存入服务器");
                List<EMMessage> moremessages = conversation.loadMoreMsgFromDB(lastMsg.getMsgId(), pagesize);
                List<EMMessage> uploadMessages;
                List<ChatMsgBean> mUploadMsg;
                mUploadMsg = new ArrayList<>();
                uploadMessages = new ArrayList<>();
                int size;
                for (int i = 0; i < moremessages.size() - 1; i++) {
                    EMMessage currMsg;
                    if (pagesize > 1) { //离线大于两条时就会将上一最后一次已读的消息读出来
                        currMsg = moremessages.get(i + 1);
                    } else {
                        currMsg = moremessages.get(i);
                    }
                    EMMessage.Direct direct = currMsg.direct();
                    switch (direct) {
                        case SEND:
                            MyLog.e(TAG, "未读消息的     msgid: " + currMsg.getMsgId() + "    消息内容: " + currMsg.getBody() + "此消息为发送,不需要重生成新消息");
                            break;
                        case RECEIVE:
                            MyLog.d(TAG, "未读消息的     msgid: " + currMsg.getMsgId() + "    消息内容: " + currMsg.getBody() + "----此消息为接收,将消息存入服务器");
                            uploadMessages.add(currMsg);
                            break;
                    }

                }
                uploadMessages.add(lastMsg);
                for (int i = 0; i < uploadMessages.size(); i++) {//展示未读消息
                    reciverHxNewMsg(uploadMessages.get(i));
                }
                //设置消息为已读
                EMClient.getInstance().chatManager().markAllConversationsAsRead();
                //TODO
//            updateMsgs(mUploadMsg,5);
                //2. 批量上传数据(批量上传)

            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> messages) {

            }

            @Override
            public void onMessageRead(List<EMMessage> var1) {

            }

            @Override
            public void onMessageDelivered(List<EMMessage> messages) {

            }

            @Override
            public void onMessageChanged(EMMessage message, Object var2) {

            }
        });
        //TODO debug模式
        EMClient.getInstance().setDebugMode(false);

//        locationService = new LocationService(getApplicationContext());
//        /***
//         * 初始化定位sdk，建议在Application中创建
//         */
//        SDKInitializer.initialize(getApplicationContext());
//        MyLog.d(TAG, "MyApp   --->   SDKInitializer.initialize(getApplicationContext())");
//        MscUtils.getInstance().initMsc(getApplicationContext());
//        MyLog.d(TAG, "MyApp   --->   MscUtils.getInstance().initMsc(getApplicationContext())");
        initHttp();
//        MyLog.d(TAG, "MyApp   --->  intiHttp");
////        initBitmapUtils();
//        MyLog.d(TAG, "MyApp   --->  initBitmapUtils");
    }


    /**
     * @param message
     */
    private void reciverHxNewMsg(final EMMessage message) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!IS_CHAT_PROGUND) {
                    HxUtils.insertOrUpdateDB(message, getApplicationContext());
                    MyLog.d(TAG, "收到离线消息,存入数据库");
                }
            }
        }).start();

    }

    /**
     * 如果是已登录，则取出UID
     */
    private void initUserInfo() {
        if (CacheUtils.getLoginStatus(getApplicationContext())) {

            loginUserUid = CacheUtils.getLoginUserid(getApplicationContext());
            if (loginUserUid == -1) {
                CacheUtils.cacheLoginStatus(getApplicationContext(), true);
            } else {
                User loginUser = UserDaoImpl.getLoginUser(getApplicationContext());
                if (loginUser != null) {
                    loginUserName = loginUser.uid + "";
                }
            }
            MyLog.e(TAG, "不需要登录，调用单点方法----------");
        }
    }

}
